package threadcoreknowledge.stopthreads.volatiledemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 对上一节 volatile无法中断线程 的修复
 * 主要是取代了使用volatile 修饰的布尔变量作为是否停止线程的标记, 而是使用了interrupt 方法来发出中断线程的信号
 * 1.3版本用 interrupt 中断来修复刚才的无尽等待问题
 */
public class WrongWayVolatileFixed {

    public static void main(String[] args) throws InterruptedException {
        WrongWayVolatileFixed body = new WrongWayVolatileFixed();

        // 阻塞队列
        ArrayBlockingQueue storage = new ArrayBlockingQueue(10);

        //生产者
        Producer producer = body.new Producer(storage);
        Thread producerThread = new Thread(producer);

        //  生产者开始生产
        producerThread.start();
        Thread.sleep(1000);

        //  消费者
        Consumer consumer = body.new Consumer(storage);
        while (consumer.needMoreNums()) {
            System.out.println(consumer.storage.take() + "被消费了");
            Thread.sleep(100);
        }

        producerThread.interrupt();
        System.out.println("消费者不需要更多数据了");

      //一旦消费不需要更多数据了，我们应该让生产者也停下来，但是实际情况
    }

    class Producer implements Runnable {

        BlockingQueue storage;

        public Producer(BlockingQueue storage) {
            this.storage = storage;
        }

        @Override
        public void run() {
            int num = 0;
            try {
                while (num <= 100000 && !Thread.currentThread().isInterrupted()) {
                    if (num % 100 == 0) {
                        storage.put(num);
                        System.out.println(num + "是100的倍数");
                    }
                    num++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("生产者停止运行");
            }
        }
    }

    class Consumer {
        BlockingQueue storage;

        public Consumer(BlockingQueue storage) {
            this.storage = storage;
        }

        public boolean needMoreNums() {
            if (Math.random() > 0.95) {
                return false;
            }
            return true;
        }
    }

}


